package middleware

import (
	"OJCenter/global"
	"OJCenter/model"
	"OJCenter/tool"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
)

func JWT(model *model.Model) gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		var data interface{}

		code = global.SUCCESS
		token := c.GetHeader("token")
		if token == "" {
			code = global.INVALID_PARAMS
		}

		claims, err := tool.ParseToken(token)
		if err != nil {
			switch err.(*jwt.ValidationError).Errors {
			case jwt.ValidationErrorExpired:
				code = global.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
			default:
				code = global.ERROR_AUTH_CHECK_TOKEN_FAIL
			}
		}
		//TODO:黑名单机制
		//uid,err:=strconv.Atoi(claims.Username)
		//if err!=nil {
		//	code = global.INVALID_PARAMS
		//}
		//isB := service.IsBlackList(int64(uid))
		//if isB {
		//	code = global.INVALID_PARAMS
		//}
		if code != global.SUCCESS {
			global.Res(c, http.StatusUnauthorized, code, data)
			c.Abort()
			return
		}
		c.Set("claims", claims.Privilege)
		c.Next()
	}
}
